xquery version "1.0";

module namespace ddi-qb='http://code.google.com/p/ddi-exist';

declare namespace ft = "http://exist-db.org/xquery/lucene";

declare namespace g = "ddi:group:3_1";
declare namespace dc="ddi:dcelements:3_1";
declare namespace d="ddi:datacollection:3_1"; 
declare namespace dc2="http://purl.org/dc/elements/1.1/"; 
declare namespace s="ddi:studyunit:3_1"; 
declare namespace c="ddi:conceptualcomponent:3_1";
declare namespace r="ddi:reusable:3_1"; 
declare namespace a="ddi:archive:3_1"; 
declare namespace ddi="ddi:instance:3_1"; 
declare namespace l="ddi:logicalproduct:3_1";


declare function ddi-qb:get-base-collection(){
    let $collection := collection('/db/ddi/data/ddi3/internal')
    return $collection
};
(: get filtered on series-id (coma separated) :)
declare function ddi-qb:get-base-collection($series as xs:string){
    let $collection := ddi-qb:get-base-collection()
    
    let $collection := if(empty($series)) 
    then
        $collection
	else
	 	$collection/ddi:DDIInstance/s:StudyUnit[r:UserID[@type='series_id'] = fn:tokenize($series,',')]
    return $collection
};

declare function ddi-qb:find-questions($query as xs:string, $lang as xs:string) {
    let $collection := ddi-qb:get-base-collection()
    let $result :=
        if(empty($lang))
        then
    		$collection//s:StudyUnit[ft:query(//r:Title, $query)]
    	else
    		$collection//d:QuestionItem[ft:query(d:QuestionText[@xml:lang=$lang], $query)]
    return $result
};
 
declare function ddi-qb:find-studies($query as xs:string, $lang as xs:string){
    let $collection := ddi-qb:get-base-collection()
    let $result := 
        if(empty($lang))
    	then
    		$collection//s:StudyUnit[ft:query(r:Citation/r:Title, $query)]
    	else
            $collection//s:StudyUnit[ft:query(r:Citation/r:Title[@xml:lang=$lang], $query)]
    
    return $result
};